const path = require('path');
const fs = require('fs');
const express = require('express');
const https = require('https');

const app = express();
const location = {
  hash: "",
  host: "www.jianshu.com",
  hostname: "www.jianshu.com",
  href: "https://www.jianshu.com/",
  origin: "https://www.jianshu.com",
  pathname: "/",
  port: "",
  protocol: "https:",
};

function proxy(req, res, next) {
  return new Promise(resolve => {
    const handle = https.get(location.origin, {
      host: location.host,
    }, response => {
      if (response.statusCode !== 200) {
        console.log('statusCode:', response.statusCode);
        resolve([response.statusCode]);
        return;
      }
      let data = '';
      response.setEncoding('utf-8');
      response.on('data', chunk => {
        data += chunk.toString();
      })
      response.on('end', () => {
        // console.log('data:\n', data);
        resolve([null, data]);
      })
    });
    handle.on('error', err => {
      resolve([err]);
    })
  });
}

app.get('/', async (req, res, next) => {
  const [err, data] = await proxy(req, res, next);
  if (err) {
    console.log('Error:\n ', err);
    return;
  }
  fs.writeFileSync(path.join(__dirname, './result.html'), data);
  const script = fs.readFileSync(path.join(__dirname, 'extra.js'), 'utf-8');
  res.end(data.replace('</body>', `<script>${script}</script></body>`));
  next();
})

app.listen(3000, () => { console.log(`Server run at 3000 port.`) });
